package org.gruposp2p.proyectokarma.gwt.client.ui;

import java.util.Set;
import org.gruposp2p.proyectokarma.gwt.client.domain.Document;
import org.gruposp2p.proyectokarma.gwt.client.json.JSONToDomain;
import org.gruposp2p.proyectokarma.gwt.client.panel.DocumentPanel;
import org.gruposp2p.proyectokarma.gwt.client.panel.SizedTagsPanel;
import org.gruposp2p.proyectokarma.gwt.client.util.RequestHelper;
import org.gruposp2p.proyectokarma.gwt.client.util.ServerPaths;
import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class StartPanel extends Composite implements SizedTagsPanel.Handler {

	private static StartPanelUiBinder uiBinder = GWT
			.create(StartPanelUiBinder.class);

	interface StartPanelUiBinder extends UiBinder<Widget, StartPanel> {	}

    @UiField VerticalPanel documentViewsPanelContainer;

	public StartPanel() {
		initWidget(uiBinder.createAndBindUi(this));
    	RequestHelper.doGet(ServerPaths.getDocumentsGetPath(50, 0), 
    			new ServerRequestCallback());
	}

	@Override
	public void handleSelectedTag(String selectedTag) {
	}
	
    private class ServerRequestCallback implements RequestCallback {

        @Override
    	public void onError(Request request, Throwable exception) {
        	new ErrorDialog().show("Exception", exception.getMessage());
        	Log.error(exception.getMessage());
    	}

        @Override
    	public void onResponseReceived(Request request, Response response) {
			Log.debug("StatusCode: " + response.getStatusCode() + 
					", Response Text: " + response.getText()); 
    		if (response.getStatusCode() == Response.SC_OK) {
                JSONValue jsonValue = JSONParser.parseLenient(response.getText());
    			Set<Document> documentSet = JSONToDomain.getDocuments(jsonValue);
    			for (Document document : documentSet) {
    				DocumentPanel documentPanel = new DocumentPanel(document);
    				documentViewsPanelContainer.add(documentPanel);
    			}
    			//EventBusManager.getInstance().fireEvent(new TagEvent(tagSet, TagEvent.Action.OBTAINED));
    		} else if (response.getStatusCode() == Response.SC_UNAUTHORIZED) {}
    		else {
            	new ErrorDialog().show("Error", "Response status: " 
            			+ response.getStatusCode());
    		}
    	}

    }
	
}
